import prisma from './prisma.service';

class RequestService {
    createFriendRequest(data: {
        senderId: string;
        receiverId: string;
        message?: string;
    }) {
        return prisma.request.create({ data, include: { sender: true } });
    }

    createGroupRequest(data: {
        senderId: string;
        groupId: string;
        message?: string;
    }) {
        return prisma.request.create({ data, include: { sender: true, group: true } });
    }

    updateRequest(id: number, status: 'ACCEPTED' | 'REJECTED') {
        return prisma.request.update({
            where: { id },
            data: { status },
            include: { sender: true, group: true }
        });
    }

    getSentRequests(userId: string) {
        return prisma.request.findMany({
            where: { senderId: userId },
            orderBy: { createdAt: 'desc' }
        });
    }

    getPendingRequests(userId: string) {
        return prisma.request.findMany({
            where: {
                status: 'PENDING',
                OR: [
                    // 1. 用户作为接收者的私聊请求
                    { receiverId: userId, groupId: null },
                    // 2. 用户管理的群组请求（OWNER 或 ADMIN）
                    {
                        group: {
                            members: {
                                some: {
                                    userId: userId,
                                    role: { in: ['OWNER', 'ADMIN'] }
                                }
                            }
                        }
                    }
                ]
            },
            include: {
                sender: true,
            },
            orderBy: { createdAt: 'desc' },
        });
    }

    getRequestById(id: number) {
        return prisma.request.findUnique({
            where: { id }
        });
    }
}

const requestService = new RequestService();
export default requestService